package kr.hkit.android_caloriecheck.adapter;

import java.util.ArrayList;

import kr.hkit.android_caloriecheck.R;
import kr.hkit.android_caloriecheck.dao.DAO;
import kr.hkit.android_caloriecheck.dto.MyItem;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DayListAdapter extends BaseAdapter {
	Context maincon;
	LayoutInflater inflater;
	ArrayList<MyItem> arList;
	int layout;
	String str;
	TextView tv;
	
	DAO dao;
	
	int year;
	int month;
	int day;
	
	public DayListAdapter(Context context, ArrayList<MyItem> arList, int layout, String str, TextView tv) {
		this.maincon = context;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.arList = arList;
		this.layout = layout;
		this.str = str;
		this.tv = tv;
		
		dao = DAO.open(maincon);
		
		SharedPreferences pref = maincon.getSharedPreferences("date", 0);
		year = pref.getInt("year", 0);
		month = pref.getInt("month", 0);
		day = pref.getInt("day", 0);
	}

	public int getCount() {
		return arList.size();
	}

	public Object getItem(int position) {
		return arList.get(position).getName();
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;

		if (convertView == null) {
			convertView = inflater.inflate(layout, parent, false);
		}

		TextView name = (TextView) convertView.findViewById(R.id.name02);
		name.setText(arList.get(position).getName());

		TextView kcal = (TextView) convertView.findViewById(R.id.kcal02);
		kcal.setText(String.valueOf(arList.get(position).getKcal()));

		Button delete = (Button) convertView.findViewById(R.id.delete);
		delete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(str.equals("food")){
					Toast.makeText(maincon,
							arList.get(pos).getName() + " 삭제",
							Toast.LENGTH_SHORT).show();

					dao.foodListDeleteByName(arList.get(pos).getName(), year, month, day);
					arList.remove(pos);
					
					int food = dao.foodkcalSumSelectByDate(year, month, day);
					tv.setText("총 섭취량 " + food + "kcal");
					
					notifyDataSetChanged();
				}else{
					Toast.makeText(maincon,
							arList.get(pos).getName() + " 삭제", Toast.LENGTH_SHORT)
							.show();

					dao.exerciseListDeleteByName(arList.get(pos).getName(), year,
							month, day);
					arList.remove(pos);
					
					int exercise = dao.exercisekcalSumSelectByDate(year, month, day);
					tv.setText("총 운동량 " + exercise + "kcal");
					
					notifyDataSetChanged();
				}
			}
		});

		return convertView;
	}
}
